#include"mystdio.h"
my_FILE* my_fopen(const char* path,const char* mode)
{
  //判断打开方式
  int iscreate = 0;//是否需要新建文件
  int _mode;
  mode_t permission = 0666;//新建文件的默认权限
  if(strcmp("r",mode) == 0)
  {
      _mode = (O_RDONLY);
  }
  else if(strcmp("w",mode) == 0)
  {
      _mode = (O_WRONLY | O_CREAT | O_TRUNC);
      iscreate = 1;
  }
  else if(strcmp("a",mode) == 0)
  {
      _mode = (O_WRONLY | O_CREAT | O_APPEND);
      iscreate = 1;
  }
  else{};
  //使用open
  int fd = 0;
  if(iscreate)
  {
   fd = open(path,_mode,permission);
  }
  else{

   fd = open(path,_mode);
  }
  //将数据填入结构体里
  my_FILE* fp  =(my_FILE*)malloc(sizeof(my_FILE));
  fp->fileno = fd;
  fp->flags = FLUSH_LINE;
  fp->cap = LINE_SIZE;
  fp->pos = 0;
  return fp;
  
}
void my_fflush(my_FILE* fp)
{
  //向数据缓冲区写入数据
  write(fp->fileno,fp->cache,fp->pos);
  fp->pos = 0;
}
int my_fwrite(my_FILE* fp,const char* data,int len)
{
  memcpy(fp->cache+fp->pos,data,len);
  fp->pos+=len;
  //满了才刷新
  if(fp->pos == LINE_SIZE)
  {
    my_fflush(fp);
  }
  return len;
}
void my_fclose(my_FILE* fp)
{
  //必须先刷新一下哎
  my_fflush(fp);
  close(fp->fileno);
  free(fp);
}
const char* file = "log.txt";
int main()
{
  my_FILE* name = my_fopen(file,"w");
  my_fwrite(name,"Hello Linux",12);
  my_fflush(name);
  my_fclose(name);
  return 0;
}
